package com.cskaoyan.user.service.impl;

import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.MemberConverter;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.UserService;
import com.google.common.base.Verify;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @USER: cuiweiguo#
 * @DATE: 2022/5/18
 * @TIME: 21:07
 * @PROJECT_NAME: duolaimall
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender sender;

    /**
     * @Description:
     * @Author: cuiweiguo#
     * @Date: 2022/5/18 21:10
     * @Param: [userLoginRequest]:
     * @return: com.cskaoyan.user.dto.UserLoginResponse:
     **/
    @Override
    public UserLoginResponse postLogin(UserLoginRequest userLoginRequest) {
        //根据传入的用户名和密码，查询数据库，返回response
        UserLoginResponse userLoginResponse = new UserLoginResponse();
        try {
            //先进行参数校验
            userLoginRequest.requestCheck();//这里知识验证了参数的合法性
            //查询数据库--member表
            Example example = new Example(Member.class);
            example.createCriteria()
                    .andEqualTo("username", userLoginRequest.getUserName())
                    .andEqualTo("password", userLoginRequest.getPassword());
            List<Member> members = memberMapper.selectByExample(example);
            //这里应该进行判断
            if (members.size() == 0) {
                userLoginResponse = memberConverter.loginReqMember(members.get(0));
                userLoginResponse.setCode(UserRetCode.DATA_NOT_EXIST.getCode());
                userLoginResponse.setMsg(UserRetCode.DATA_NOT_EXIST.getMessage());
                return userLoginResponse;
            }
            System.out.println(members.get(0).getIsVerified());
            //如果用户已经注册，但是没有激活
            if ("N".equals(members.get(0).getIsVerified())){
                userLoginResponse = memberConverter.loginReqMember(members.get(0));
                userLoginResponse.setCode(UserRetCode.USER_ISVERFIED_ERROR.getCode());
                userLoginResponse.setMsg(UserRetCode.USER_ISVERFIED_ERROR.getMessage());
                return userLoginResponse;
            }
            //根据注册规则，不存在同名，同密码的user,所以直接else
            //此时将查询到的member转为为userLoginResponse
            userLoginResponse = memberConverter.loginReqMember(members.get(0));
            userLoginResponse.setCode(UserRetCode.SUCCESS.getCode());
            userLoginResponse.setMsg(UserRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return userLoginResponse;
    }

    @Override
    public UserGetInfoRequest queryMemberForGetLogin(UserGetInfoRequest userGetInfoRequest) {
        UserGetInfoRequest userGetInfo = new UserGetInfoRequest();
        Member member = memberMapper.selectByPrimaryKey(userGetInfoRequest.getUid());
        userGetInfo.setUid(userGetInfoRequest.getUid());
        userGetInfo.setFile(member.getFile());
        return userGetInfo;
    }

    @Override
    public UserRegisterResponse registerUser(UserRegisterRequest userRegisterRequest) {
        UserRegisterResponse response = new UserRegisterResponse();
        //先进行参数校验
        userRegisterRequest.requestCheck();
        //然后查询数据库是否用户名重复
        int count = userNameRepate(userRegisterRequest.getUserName());
        if (count != 0) {
            response.setCode(UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }
        //然后查询数据库是否邮箱重复
        int count2 = userEmailRepate(userRegisterRequest.getEmail());
        if (count2 != 0) {
            response.setCode(UserRetCode.USERNAME_ALREADY_EXISTS.getCode());
            response.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            return response;
        }
        //member表插入一条数据
        Member member = new Member();
        member.setUsername(userRegisterRequest.getUserName());
        member.setPassword(userRegisterRequest.getUserPwd());
        member.setEmail(userRegisterRequest.getEmail());
        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);
        int affectedRows = memberMapper.insertSelective(member);
        if (affectedRows!=1){
            response.setCode(UserRetCode.USER_REGISTER_FAILED.getCode());
            response.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //向验证表中插入一条信息
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(userRegisterRequest.getUserName());
        userVerify.setRegisterDate(new Date());
        String uuid = UUID.randomUUID().toString();
        userVerify.setUuid(uuid);
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int affectRow = userVerifyMapper.insert(userVerify);
        if (affectRow!=1){
            response.setCode(UserRetCode.USEREMAIL_ALREADY_EXISTS.getCode());
            response.setMsg(UserRetCode.USEREMAIL_ALREADY_EXISTS.getMessage());
            return response;
        }
        //TODO:向用户发送邮件---优化为异步发送

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("账户激活验证");
        simpleMailMessage.setTo(userRegisterRequest.getEmail());
        simpleMailMessage.setFrom("oppozhuimeng@163.com");
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://localhost:9999/user/verify?username=").append(userRegisterRequest.getUserName()).append("&uuid=").append(uuid);
        simpleMailMessage.setText(stringBuilder.toString());
        sender.send(simpleMailMessage);

        //注册成功
        response.setCode(UserRetCode.SUCCESS.getCode());
        response.setMsg(UserRetCode.SUCCESS.getMessage());
        return response;
    }
    /**
     * @Description:  用户激活
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 16:29
     * @Param: [userVerify]:
     * @return: void:
     **/
    @Override
    public void verifyUser(UserVerify userVerify) {
        //更新member表
        Member member = new Member();
        member.setIsVerified("Y");
        member.setUpdated(new Date());
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username",userVerify.getUsername());
        memberMapper.updateByExampleSelective(member,example);
        //跟新验证表verify
        UserVerify user = new UserVerify();
        user.setIsVerify("Y");
        Example veryExample = new Example(UserVerify.class);
        veryExample.createCriteria()
                .andEqualTo("username",userVerify.getUsername())
                .andEqualTo("uuid",userVerify.getUuid());
        userVerifyMapper.updateByExampleSelective(user,veryExample);
        //TODO:对结果尽心判断
    }

    /**
     * @Description: 验证用户注册邮箱是否重复
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 14:57
     * @Param: [email]:
     * @return: void:
     **/
    private int userEmailRepate(String email) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("email", email);
        int count = memberMapper.selectCountByExample(example);
        //如果不为0，则表示有重复，则抛出异常
        return count;
    }

    /**
     * @Description: 验证用户名是否重复
     * @Author: cuiweiguo#
     * @Date: 2022/5/19 14:55
     * @Param: [userName]:
     * @return: void:
     **/
    private int userNameRepate(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username", userName);
        int count = memberMapper.selectCountByExample(example);
        //如果不为0，则表示有重复，则抛出异常
       return count;
    }
}
